package shard

import (
	"hash"
	"hash/fnv"
	"strconv"
	"time"
)

const (
	_shardDateFormat  = "20060102"
	_shardYearFormat  = "2006"
	_shardMonthFormat = "200601"
)

//key生成接口，通过算法生成一个uint值
type Key interface {
	Get() (uint, string)
}

//直接long值uint 返回结构体传入的uint值
type LongKey struct {
	value uint
}

func (v *LongKey) Get() (uint, string) {
	return v.value, strconv.Itoa(int(v.value))
}

//快捷创建一个Longkey struct
func NewLongKey(v uint) *LongKey {
	return &LongKey{value: v}
}

//通过string 值hash算法来生成uint,默认使用fnvHash32
type HashKey struct {
	value string
}

var fnvHash32 hash.Hash32 = fnv.New32()

func (v *HashKey) Get() (uint, string) {
	hash, _ := fnvHash32.Write([]byte(v.value))
	return uint(hash), strconv.Itoa(int(hash))
}

//快捷创建一个NewHashKey struct
func NewHashKey(v string) *HashKey {
	return &HashKey{value: v}
}

//日期值key，根据传入的时间和格式来确定日期值
type DateKey struct {
	time   time.Time
	format string
}

func (v *DateKey) Get() (uint, string) {
	str := v.time.Format(v.format)
	seed, err := strconv.ParseUint(str, 10, 0)
	panic(err)
	return uint(seed), strconv.Itoa(int(seed))
}

//创建以年月日DateKey实例，格式为：20060102
func NewDateKey(t time.Time) *DateKey {
	return &DateKey{time: t, format: _shardDateFormat}
}

//创建以年月DateKey实例，格式为：200601
func NewMonthKey(t time.Time) *DateKey {
	return &DateKey{time: t, format: _shardMonthFormat}
}

//创建以年DateKey实例，格式为：2006
func NewYeayKey(t time.Time) *DateKey {
	return &DateKey{time: t, format: _shardYearFormat}
}
